package com.rz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.admin.entity.Admin;
import com.rz.core.exception.GlobalException;
import com.rz.admin.entity.Consumer;
import com.rz.admin.mapper.ConsumerMapper;
import com.rz.admin.service.IConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author maweiyue
 * @Date 2019/07/01
 * @Description 客户管理
 */
@Component
public class ConsumerServiceImpl extends ServiceImpl<ConsumerMapper, Consumer> implements IConsumerService {

    @Autowired
    private AdminService adminService;

    /**
     * 翻页查询
     * @param consumer
     * @return
     */
    public IPage<Consumer> getPage(Consumer consumer) {
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(consumer.getName())) {
            queryWrapper.eq("name", consumer.getName());
        }
        if (StringUtils.isNotEmpty(consumer.getCode())) {
            queryWrapper.eq("code", consumer.getCode());
        }
        Admin admin = adminService.getById(consumer.getCrteMngId());
        if (admin != null) {
            // 查询该用户下属所有客户信息
            List<Integer> childrenIds = this.listChildrenIds(admin.getOrgId());
            childrenIds.add(admin.getOrgId());
            queryWrapper.in("parent_id", childrenIds);
            queryWrapper.or();
            queryWrapper.eq("id", admin.getOrgId());
        }
        queryWrapper.eq("del_flag", 0);
        Page<Consumer> page = new Page<>(consumer.getPageNo(), consumer.getPageSize());
        IPage<Consumer> desktopIPage = page(page, queryWrapper);
        return desktopIPage;
    }

    /**
     * 新增/更新客户信息
     *
     * @param consumer
     * @return
     */
    public boolean onSave(Consumer consumer) {
        if (consumer.getId() == null) {
            if (this.getByName(consumer.getName()) != null) {
                throw new GlobalException("客户“" + consumer.getName() + "”已存在！");
            }
            consumer.setDelFlag(0);
            consumer.setCrteTime(LocalDateTime.now());
        } else {
            Consumer old = this.getByName(consumer.getName());
            if (!consumer.getId().equals(old.getId())) {
                throw new GlobalException("客户“" + consumer.getName() + "”已存在！");
            }
        }
        boolean isOK = this.saveOrUpdate(consumer);
        return isOK;
    }


    public Consumer getByName(String name){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", name);
        queryWrapper.eq("del_flag", 0);
        List<Consumer> list = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 逻辑删除客户信息
     *
     * @param id
     * @return
     */
    public boolean delete(Integer id) {
        Consumer consumer = this.getById(id);
        if (consumer != null) {
            consumer.setDelFlag(1);
            boolean isOK = this.saveOrUpdate(consumer);
            return isOK;
        } else {
            throw new GlobalException("客户信息不存在！");
        }
    }

    /**
     * 根据创建者id获取组织机构列表
     *
     * @param crteMngId
     * @return
     */
    public List<Consumer> getByCreteMngId(Integer crteMngId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("crte_Mng_Id", crteMngId);
        queryWrapper.eq("del_flag", 0);
        return list(queryWrapper);
    }

    /**
     * 列出包含自身的所有下级单位列表
     *
     * @param mngId 当前系统操作用户id
     * @return
     */
    public Consumer listConsumerTree(Integer mngId) {
        Admin admin = this.adminService.getById(mngId);
        if (admin != null && (admin.getOrgId() != null && !admin.getOrgId().equals(0))) {
            Consumer consumer = this.getById(admin.getOrgId());
            consumer.setChildren(this.getChildrenTree(admin.getOrgId()));
            return consumer;
        }

        return null;
    }


    public List<Consumer> getChildrenTree(Integer id) {
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        queryWrapper.eq("del_flag", 0);
        List<Consumer> list = list(queryWrapper);
        if (list != null && list.size() > 0) {
            for (Consumer consumer : list) {
                consumer.setChildren(getChildrenTree(consumer.getId()));
            }
        }
        return list;
    }

    /**
     * 获取指定客户自己以及所有下级客户
     *
     * @param consumerId
     * @return
     */
    public List<Consumer> listChildren(Integer consumerId) {
        List<Consumer> result = new ArrayList<>();
        Consumer consumer = this.getById(consumerId);
        if (consumer != null) {
            result.add(consumer);
            this.getChildren(consumerId, result);
        }
        return result;
    }

    public void getChildren(Integer id, List<Consumer> result) {
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        queryWrapper.eq("del_flag", 0);
        List<Consumer> list = list(queryWrapper);
        if (list != null && list.size() > 0) {
            for (Consumer consumer : list) {
                result.add(consumer);
                getChildren(consumer.getId(), result);
            }
        }
    }

    /**
     * 获取指定客户的所有下级客户id（包括下级的下级，但不包含自身）
     *
     * @param consumerId
     * @return
     */
    public List<Integer> listChildrenIds(Integer consumerId) {
        List<Integer> result = new ArrayList<>();
        this.getChildrenIds(consumerId, result);
        return result;
    }

    public void getChildrenIds(Integer id, List<Integer> result) {
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        queryWrapper.eq("del_flag", 0);
        List<Consumer> list = list(queryWrapper);
        if (list != null && list.size() > 0) {
            for (Consumer consumer : list) {
                result.add(consumer.getId());
                getChildrenIds(consumer.getId(), result);
            }
        }
    }
}
